package com.hyl.uitl;

import com.hyl.controller.UserController;
import org.apache.commons.io.FilenameUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

/**
 * @Description TODO
 * @Author com.hyl
 * @Date 2022/10/15 9:54
 **/
public class FileUtil {

   private static Logger logger = Logger.getLogger(FileUtil.class);

	/**
	 * 上传图片
	 * @param request
	 * @param idPic
	 * @return
	 */
	public static String upload(HttpServletRequest request, MultipartFile idPic){
		String idPicPath = null;
		//判断文件是否为空
		if(!idPic.isEmpty()){
			String path = request.getSession().getServletContext().getRealPath("statics"+ File.separator+"uploadfiles");
			logger.info("上传文件路径"+path);
			String originalFile = idPic.getOriginalFilename();//原文件名
			logger.info("源文件名为："+originalFile);
			String prefix= FilenameUtils.getExtension(originalFile);//原文件后缀
			logger.debug("原文件后缀为：" + prefix);
			if(prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png")
					|| prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")){//上传图片格式不正确
				String fileName = System.currentTimeMillis()+"_Personal." + prefix;
				logger.debug("新生成的文件名称为：" + idPic.getName());
				File targetFile = new File(path);
				if(!targetFile.exists()){
					targetFile.mkdirs();
				}
				//保存
				try {
					idPic.transferTo(new File(targetFile, fileName));
				} catch (Exception e) {
					e.printStackTrace();
					logger.info("上传出错");
				}
				idPicPath = File.separator+"statics"+ File.separator+"uploadfiles" + File.separator+fileName;
			}else{
				logger.info("文件格式不正确");
			}
		}
		return idPicPath;
	}
}
